home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 4318 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  79 lines

  1. Path: rz.uni-passau.de!piligrim!berndl
  2. From: berndl@piligrim.uni-passau.de (Klaus Berndl)
  3. Newsgroups: comp.lang.c
  4. Subject: Allocation of memory
  5. Date: 3 Feb 1996 14:28:25 GMT
  6. Organization: University of Passau, Germany
  7. Sender: berndl@piligrim (Klaus Berndl)
  8. Distribution: world
  9. Message-ID: <4evre9$8r4@news.rz.uni-passau.de>
  10. NNTP-Posting-Host: 132.231.1.72
  11. Keywords: realloc
  12.  
  13. today i have a not-RPC-problem, but perhaps you can solve it:
  14.  
  15. Please look at the foolwing short piece of code:
  16.  
  17. #include <stdlib.h>
  18. #include <malloc.h>
  19.  
  20. #define ALLOCSIZE 100000000
  21.  
  22. extern char* strcpy();
  23.  
  24. main () {
  25.  
  26.   char* t = NULL;
  27.   char* temp = NULL;
  28.   char* x = NULL;
  29.   
  30.   t = (char*)realloc(t, 1000);
  31.   strcpy (t, "Klaus");
  32.   printf("\n%s\n", t);
  33.   temp = t;
  34.   if ((t = (char*)realloc(t, ALLOCSIZE)) == NULL) {
  35.     printf("\n t-realloc failed\n");
  36.     t = temp;
  37.   }
  38.   printf("\ntest1\n");  
  39.   if ((x = (char*)realloc(x, 1000000)) == NULL) {
  40.     printf("\n x-realloc failed\n");
  41.   }
  42.   printf("\ntest2\n");  
  43.   printf("\n%s\n", t);
  44. }
  45.  
  46. Now my questions:
  47.  
  48. 1) How is it possible, that my machine (Sparc classic) allocates 100MB
  49.    Storage? I`m sure i have not so much main memory installed. Does it
  50.    use swap-file??
  51. 2) With ALLOCSIZE set to 100000000 the program works correct. But if i set
  52.    ALLOCSIZE to 300000000, i reach the following output:
  53.  
  54.      Klaus
  55.  
  56.       t-realloc failed
  57.  
  58.      test1
  59.      Bus Error (core dumped)
  60.  
  61.    What is 'realloc' doing exactly? Normally if realloc can`t allocate the
  62.    requested memory it returns NULL and doesn`t allocate memory. Why the 
  63.    second realloc-call (x = ...) fails? There must be 1000000 Byte memory
  64.    because of the first try with ALLOCSIZE 100000000 works!
  65.  
  66. 3) We are comming to the point: I must succesive realloc storage for a 
  67.    certain variable v. And if realloc fails, i want have the recent correct
  68.    memory allocation for v containing the right value (look at 'temp' in the
  69.    code). I need a save solution! 
  70.  
  71.  
  72. Ciao,
  73.       Klaus
  74.  
  75. ____________________________________________________________________________
  76.  
  77. Klaus Berndl                                e-mail: berndl@fmi.uni-passau.de
  78. ____________________________________________________________________________
  79.